<template>
  <div>
    <el-button type="primary" @click="openAddDialog">添加科研项目</el-button>
    <el-table :data="projects" style="margin-top: 10px" border>
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="项目名称" />
      <el-table-column prop="projectType" label="项目类型" width="120" />
      <el-table-column prop="role" label="角色" width="120" />
      <el-table-column prop="score" label="评分" width="100" />
      <el-table-column prop="year" label="年份" width="100" />
      <el-table-column label="操作" width="160">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisible" title="科研项目" @close="resetForm">
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="formData.name" />
        </el-form-item>
        <el-form-item label="项目类型" prop="projectType">
          <el-select v-model="formData.projectType" placeholder="请选择项目类型" style="width: 100%">
            <el-option label="创新项目" value="创新项目" />
            <el-option label="导师项目" value="导师项目" />
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-input v-model="formData.role" />
        </el-form-item>
        <el-form-item label="评分" prop="score">
          <el-input-number 
            v-model="formData.score" 
            :min="0" 
            :max="100" 
            :precision="2"
            :step="0.01"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="年份" prop="year">
          <el-input-number v-model="formData.year" :min="2000" :max="2100" style="width: 100%" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
export default {
  name: "ResearchProjectsModule",
  props: {
    studentId: { type: Number, required: true },
  },
  data() {
    return {
      projects: [],
      dialogVisible: false,
      formData: this.initFormData(),
      rules: {
        name: [{ required: true, message: "请输入项目名称", trigger: "blur" }],
        projectType: [{ required: true, message: "请选择项目类型", trigger: "change" }],
        role: [{ required: true, message: "请输入角色", trigger: "blur" }],
        score: [
          {
            type: "number",
            min: 0,
            max: 100,
            message: "评分需在0到100之间",
            trigger: "change",
          },
        ],
        year: [
          {
            type: "number",
            min: 2000,
            max: 2100,
            message: "年份需在2000到2100之间",
            trigger: "change",
          },
        ],
      },
    };
  },
  watch: {
    studentId: {
      handler(newVal) {
        if (typeof newVal === "number" && !isNaN(newVal)) {
          this.loadData();
        } else {
          this.projects = [];
        }
      },
      immediate: true,
    },
  },
  methods: {
    initFormData() {
      return {
        id: null,
        studentId: this.studentId,
        name: "",
        projectType: "",
        role: "",
        score: null,
        year: null,
      };
    },
    async loadData() {
      try {
        const res = await axios.get(`/api/researchprojects/student/${this.studentId}`);
        if (res.data.code === 200) {
          this.projects = res.data.data || [];
        } else {
          this.$message.error(res.data.message || "加载科研项目失败");
        }
      } catch (e) {
        this.$message.error("加载科研项目失败");
        console.error("加载科研项目失败", e);
      }
    },
    openAddDialog() {
      this.formData = this.initFormData();
      this.dialogVisible = true;
    },
    handleEdit(row) {
      this.formData = { ...row, studentId: this.studentId };
      this.dialogVisible = true;
    },
    async submit() {
      try {
        this.formData.studentId = this.studentId;
        const valid = await this.$refs.formRef.validate();
        if (!valid) return;

        let res;
        if (this.formData.id) {
          res = await axios.put("/api/researchprojects", this.formData);
        } else {
          res = await axios.post("/api/researchprojects", this.formData);
        }

        if (res.data.code === 200) {
          this.$message.success(res.data.message || (this.formData.id ? "更新成功" : "添加成功"));
          this.dialogVisible = false;
          await this.loadData();
          this.$emit("save-success");
        } else {
          this.$message.error(res.data.message || (this.formData.id ? "更新失败" : "添加失败"));
        }
      } catch (e) {
        this.$message.error("提交失败");
        console.error("提交失败", e);
      }
    },
    async handleDelete(id) {
      try {
        const res = await axios.delete(`/api/researchprojects/${id}`);
        if (res.data.code === 200) {
          this.$message.success(res.data.message || "删除成功");
          await this.loadData();
          this.$emit("save-success");
        } else {
          this.$message.error(res.data.message || "删除失败");
        }
      } catch (e) {
        this.$message.error("删除失败");
        console.error("删除失败", e);
      }
    },
    resetForm() {
      this.$refs.formRef?.resetFields();
      this.formData = this.initFormData();
    },
  },
};
</script>
